'use client';

import type { IMenu } from '@/interfaces';
import type { TBody } from '@/types';
import { queryMenus, removeMenu } from '@/services/api';
import { type ChangeEvent, useContext, useState } from 'react';
import { useMutation, useQuery } from '@tanstack/react-query';
import classNames from 'classnames';
import { MENU_TYPE_KEY } from '@/lib/constant';
import useToast from '@/hooks/useToast';
import Alert from '@/app/[locale]/alert/alert';
import AlertLoad from '@/app/[locale]/alert/load';
import { MenuAdminContext } from '@/contexts/admin/menu';
import DetailsMenuAdminPage from '@/app/[locale]/admin/menu/detail';
import UpdateMenuAdminPage from '@/app/[locale]/admin/menu/update';
import CreateMenuAdminPage from '@/app/[locale]/admin/menu/create';
import CreateSubmenuAdminPage from '@/app/[locale]/admin/menu/create/submenu';

export default function ListMenuAdminPage(this: any) {
  const [currentItemId, setCurrentItemId] = useState<number>();
  const [searchName, setSearchName] = useState('');
  const { show } = useToast();
  const [isCreate, setIsCreate] = useState(false);
  const [isCreateSubmenu, setIsCreateSubmenu] = useState(false);
  const [detailItem, setDetailItem] = useState<IMenu>();
  const [updateItem, setUpdateItem] = useState<IMenu>();
  const context = useContext(MenuAdminContext);
  const queryKey = ['/menus', searchName];

  const queryMenusQuery = useQuery(
    queryKey,
    async (context) => {
      return searchCore((await queryMenus()) as IMenu[], context.queryKey[1]);
    },
    {
      keepPreviousData: true,
    },
  );

  const removeMenuMutation = useMutation(async (variables: TBody<void>) => {
    await removeMenu(variables);
    await queryMenusQuery.refetch({ throwOnError: true });
  });

  function searchCore(data: IMenu[], searchName: string) {
    return searchName
      ? data.filter((item) => {
          return (
            item.name.includes(searchName) ||
            item.path.includes(searchName) ||
            (searchName === '链接' && item.menuType === 'LINK') ||
            (searchName === '按钮' && item.menuType === 'BUTTON')
          );
        })
      : data;
  }

  async function onClickRemove() {
    try {
      await removeMenuMutation.mutateAsync({
        id: currentItemId,
      });

      show({
        type: 'SUCCESS',
        message: '删除完成',
      });
    } catch (e) {
      removeMenuMutation.reset();
      show({
        type: 'DANGER',
        message: e,
      });
    }
  }

  function onChangeSearch(e: ChangeEvent<HTMLInputElement>) {
    const value = e.target.value;
    setSearchName(value.toLowerCase() || '');
  }

  function onClickCreateSubmenu() {
    setIsCreateSubmenu(true);
  }

  function onClickCreate() {
    setIsCreate(true);
  }

  function onClickDetail(item: IMenu) {
    setDetailItem(item);
    setCurrentItemId(item.id);
  }

  function onClickUpdate(item: IMenu) {
    setUpdateItem(item);
  }

  if (queryMenusQuery.data) {
    const data = queryMenusQuery.data;

    return (
      <MenuAdminContext.Provider
        value={{
          ...context,
          isCreate,
          isCreateSubmenu,
          detailItem,
          updateItem,
          setIsCreate,
          setIsCreateSubmenu,
          setDetailItem,
          setUpdateItem,
          queryKey,
        }}
      >
        <div className="row">
          <div className="col">
            <div className="vstack gap-4">
              {isCreate ? (
                <CreateMenuAdminPage />
              ) : isCreateSubmenu ? (
                <CreateSubmenuAdminPage />
              ) : (
                <div className="row">
                  <div className="col">
                    <div className="card">
                      <div className="card-header bg-transparent">
                        <div className="row row-cols-auto justify-content-between g-2">
                          <div className="col">
                            <div className="input-group">
                              <span className="input-group-text">
                                <i className="bi bi-search"></i>
                              </span>
                              <input
                                onChange={onChangeSearch}
                                type="search"
                                className="form-control"
                                placeholder="搜索菜单"
                              />
                            </div>
                          </div>
                          <div className="col">
                            <div className="hstack gap-3">
                              {currentItemId && (
                                <button
                                  onClick={onClickRemove}
                                  disabled={removeMenuMutation.isLoading}
                                  type="button"
                                  className="btn btn-danger"
                                >
                                  <i className="bi bi-trash me-2"></i>
                                  删除菜单
                                </button>
                              )}

                              {currentItemId && (
                                <button
                                  onClick={onClickCreateSubmenu}
                                  type="button"
                                  className="btn btn-primary"
                                >
                                  <i className="bi bi-list-nested me-2"></i>
                                  新增子菜单
                                </button>
                              )}

                              <button
                                onClick={onClickCreate}
                                type="button"
                                className="btn btn-primary"
                              >
                                <i className="bi bi-menu-button me-2"></i>
                                新增菜单
                              </button>
                            </div>
                          </div>
                        </div>
                      </div>
                      <div className="card-body">
                        <div className="table-responsive">
                          <table className="table table-hover align-middle">
                            <thead>
                              <tr className="text-nowrap">
                                <th scope="col" className="w-10">
                                  ID
                                </th>
                                <th scope="col" className="w-10">
                                  名称
                                </th>
                                <th scope="col" className="w-10">
                                  路径
                                </th>
                                <th scope="col" className="w-10">
                                  排序
                                </th>
                                <th scope="col" className="w-10">
                                  类型
                                </th>
                                <th scope="col" className="w-10"></th>
                              </tr>
                            </thead>
                            <tbody>
                              {data.map((item) => {
                                return (
                                  <tr
                                    key={item.id}
                                    className={classNames('text-nowrap', {
                                      'table-active': currentItemId === item.id,
                                    })}
                                  >
                                    <td
                                      className="cursor-pointer"
                                      onClick={onClickDetail.bind(this, item)}
                                    >
                                      {item.id}
                                    </td>
                                    <td
                                      className="cursor-pointer"
                                      onClick={onClickDetail.bind(this, item)}
                                    >
                                      {item.name}
                                    </td>
                                    <td
                                      className="cursor-pointer"
                                      onClick={onClickDetail.bind(this, item)}
                                    >
                                      {item.path}
                                    </td>
                                    <td
                                      className="cursor-pointer"
                                      onClick={onClickDetail.bind(this, item)}
                                    >
                                      {item.sort}
                                    </td>
                                    <td
                                      className="cursor-pointer"
                                      onClick={onClickDetail.bind(this, item)}
                                    >
                                      {MENU_TYPE_KEY[item.menuType]}
                                    </td>
                                    <td>
                                      <button
                                        onClick={onClickUpdate.bind(this, item)}
                                        className="btn btn-sm btn-light"
                                        type="button"
                                      >
                                        <i className="bi bi-pencil me-2"></i>
                                        修改
                                      </button>
                                    </td>
                                  </tr>
                                );
                              })}
                            </tbody>
                          </table>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              )}

              {detailItem && <DetailsMenuAdminPage />}

              {updateItem && <UpdateMenuAdminPage />}
            </div>
          </div>
        </div>
      </MenuAdminContext.Provider>
    );
  }

  if (queryMenusQuery.error) {
    return <Alert message={queryMenusQuery.error} type="error" />;
  }

  return <AlertLoad />;
}
